package com.mo.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.mo.domain.User;
import com.mo.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author msy
 * @date 2022/3/28
 */
@Slf4j
@Service
public class ExportServiceImp {

    @Autowired
    private UserMapper userMapper;

    /**
     * 所有用户数据集合
     *
     * @return 所有用户数据集合
     */
    public List<User> export() {
        return userMapper.selectUserList(null);
    }

    /**
     * 批量导入数据
     *
     * @param file
     * @return 新增的行数
     */
    public int importExcel(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        //匿名内部类
        List<User> list = EasyExcel.read(inputStream, User.class, new ReadListener<User>() {
            //单次缓存数据量
            public static final int BATCH_COUNT = 100;
            //创建指定长度集合，临时存储
            private List<User> list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

            @Override
            public void invoke(User user, AnalysisContext analysisContext) {
                list.add(user);
                if (list.size() >= BATCH_COUNT) {
                    saveData();
                    //存储完成清理集合
                    list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                //防止遗留数据
                saveData();
            }

            private void saveData() {
                log.info("开始保存{}条数据", list.size());
                userMapper.save(list);
                log.info("保存完毕");
            }
        }).sheet().doReadSync();
/*      save方法空指针异常，依赖注入没有注入
        EasyExcel.read(inputStream,User.class,new Listener<User>(ExportServiceImp.class)).sheet().doRead();
*/
        return 0;
    }

    private int save(List<User> list) {
        return userMapper.save(list);
    }

}
